package cn.edu.nwsuaf.examcenter.aop;

import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;


import org.apache.log4j.Logger;
import org.springframework.aop.AfterReturningAdvice;
import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.aop.ThrowsAdvice;

/****
 * 动态切换数据源  用于配置主从数据库
 * @author Fantacy
 *
 */
public class DataSourceAdvice implements MethodBeforeAdvice, AfterReturningAdvice, ThrowsAdvice {


	// 日志
	private Logger log = Logger.getLogger(DataSourceAdvice.class);


	// 选用主数据库的方法前缀
	public static Set<String> masterMethod = new HashSet<String>();
	
	// 选用从数据库的方法前缀
	public static Set<String> slaveMethod = new HashSet<String>();

	static {
			masterMethod.add("singleDataInsert");
			masterMethod.add("batchDataInsert");
			masterMethod.add("singleDataDelete");
			masterMethod.add("batchDataDelete");
			masterMethod.add("singleDataUpdate");
			masterMethod.add("batchDataUpdate");
			
			slaveMethod.add("findAll");
			slaveMethod.add("findById");
			slaveMethod.add("findDataByPage");
			slaveMethod.add("countData");
	}


	@Override
	public void before(Method method, Object[] args, Object target) throws Throwable {
		String methodName = method.getName();
		log.info("__________________切入点: " + target.getClass().getName() + "类中" + methodName + "方法");
		if (masterMethod.contains(methodName)) {
			log.info("__________________切换到主数据库");
			DataSourceSwitcher.setMaster();
		} else if (slaveMethod.contains(methodName)) {
			log.info("__________________切换到从数据库");
			DataSourceSwitcher.setSlave();
		} else {
			log.info("__________________没有找到要切换的数据库");
		}
	}


	@Override
	public void afterReturning(Object arg0, Method method, Object[] args, Object target) throws Throwable {
	}


	/**
	 * 抛出Exception之后被调用
	 * 
	 * @param method
	 * @param args
	 * @param target
	 * @param ex
	 * @throws Throwable
	 */
	public void afterThrowing(Method method, Object[] args, Object target, Exception ex) throws Throwable {
		DataSourceSwitcher.setSlave();
		log.info("出现异常,切换到: slave");
	}
}
